<template>
  <div class="household-query">
    <el-card>
      <template #header>
        <span>户口综合查询</span>
      </template>
      
      <!-- 查询条件 -->
      <el-form :model="queryForm" :inline="true" class="query-form">
        <el-form-item label="姓名">
          <el-input v-model="queryForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="queryForm.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="户籍地址">
          <el-input v-model="queryForm.address" placeholder="请输入户籍地址" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 查询结果 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="idCard" label="身份证号" />
        <el-table-column prop="gender" label="性别">
          <template #default="{ row }">
            {{ formatGender(row.gender) }}
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期">
          <template #default="{ row }">
            {{ formatDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="户籍地址" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="text" @click="viewDetail(row)">查看详情</el-button>
            <el-button type="text" @click="editRecord(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'

const loading = ref(false)
const tableData = ref([])

const queryForm = reactive({
  name: '',
  idCard: '',
  address: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取户口列表数据
const fetchHouseholdList = async () => {
  loading.value = true
  
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    // 构建查询参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    // 添加查询条件（只有非空值才添加）
    if (queryForm.name && queryForm.name.trim()) {
      params.name = queryForm.name.trim()
    }
    if (queryForm.idCard && queryForm.idCard.trim()) {
      params.idCard = queryForm.idCard.trim()
    }
    if (queryForm.address && queryForm.address.trim()) {
      params.address = queryForm.address.trim()
    }

    console.log('发送查询请求，参数:', params)

    const response = await axios.get(`${API_BASE_URL}/household/list`, {
      params: params,
      headers: {
        'token': token
      }
    })

    console.log('查询响应:', response.data)

    if (response.data.status === 200) {
      tableData.value = response.data.data || []
      // 注意：后端暂时没有返回总数，这里先设置为数据长度
      // 实际项目中应该后端返回总数用于分页
      pagination.total = tableData.value.length
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(response.data.msg || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  // 重置到第一页
  pagination.currentPage = 1
  fetchHouseholdList()
}

const handleReset = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = ''
  })
  // 重置后重新查询
  handleQuery()
}

const viewDetail = (row) => {
  ElMessage.info(`查看 ${row.name} 的详细信息`)
}

const editRecord = (row) => {
  ElMessage.info(`编辑 ${row.name} 的信息`)
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1 // 重置到第一页
  fetchHouseholdList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchHouseholdList()
}

// 格式化性别显示
const formatGender = (gender) => {
  if (gender === 1) return '男'
  if (gender === 2) return '女'
  return '未知'
}

// 格式化日期显示
const formatDate = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  fetchHouseholdList()
})
</script>

<style lang="scss" scoped>
.household-query {
  .query-form {
    margin-bottom: 20px;
  }
}
</style>